package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"shenzhou-b/api/pkg"
	"time"

	"shenzhou-b/api/internal/svc"
	"shenzhou-b/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadImgStatusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadImgStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadImgStatusLogic {
	return &UploadImgStatusLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadImgStatusLogic) UploadImgStatus(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("img")
	if err != nil {
		return nil, err
	}
	if float64(m.Size) > 0.2*float64(1024*1024) {
		return &types.Response{
			Code: 500,
			Msg:  "文件大小不超过200kb",
			Data: nil,
		}, nil
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".jpg" && ext != ".png" {
		return &types.Response{
			Code: 500,
			Msg:  "图片格式仅为 png、jpg",
			Data: nil,
		}, nil
	}
	name := time.Now().Format("20060102150405") + ext
	upload, err := pkg.Upload(file, name)
	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  err.Error(),
			Data: nil,
		}, nil
	}

	return &types.Response{
		Code: 200,
		Msg:  "上传成功",
		Data: map[string]interface{}{"upload": upload},
	}, nil
}
